package org.gary.base.action;

import static lengreen.util.constant.Constant.DateFomaterString.YYYY_MM_DD_HH_MM_SS;
import static org.gary.core.util.Utils.*;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.gary.base.model.Image;
import org.gary.base.model.Link;
import org.gary.base.service.ImageService;
import org.gary.base.service.LinkService;
import org.gary.core.service.InitService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * @author lengreen
 * 
 */
@Component
@Scope("prototype")
public class LinkAction extends ActionSupport implements ServletResponseAware,
		SessionAware {
	private static final long serialVersionUID = -1520130061367054089L;
	private HttpServletResponse response;
	private Map<String, Object> session;
	
	private LinkService linkService;
	private ImageService imageService;
	private InitService initService;
	private Link link;
	private List<Link> linkList;
	private File linkImage;
	private String linkImageFileName;
	private String linkImageContentType;
	/**分页开始页*/
	private int start;
	/**分页最大记录数*/
	private int limit;
	/**是否可见*/
	private String visible;
	/**搜索参数url*/
	private String url;
	/**搜索参数开始时间*/
	private String fromDate;
	/**结束时间*/
	private String toDate;
	/**删除模式*/
	private String mode;
	/**通过uuid生成的图片名，可当做id使用*/
	private String imageName;
	/**返回结果字符串*/
	private String result;

	/**
	 * 添加
	 * @throws IOException
	 */
	public void add() throws IOException {
		try {
			if (link != null) {
				Image image = handleImageUpload(linkImage, linkImageFileName,
						"LinkImage", BUFFER_SIZE);
				if (image != null) {
					imageService.save(image);
					link.setImage(imageService.loadByName(image.getName()));
				}
				if (link.getUrl().indexOf("http://") == -1) {
					link.setUrl("http://" + link.getUrl());
				}
				linkService.save(link);
				initService.minLinks(session);
				result = "{'success':'true'}";
			} else {
				result = "{'success':'false'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 列表
	 * @throws IOException
	 */
	public void list() throws IOException {
		start = parseIndex(start, limit);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(getVisible()));
		setLinkList(linkService.list(Link.class, getStart(), getLimit(), where,
				new Object[] { " entity.id desc " }));

		for (Link p : linkList) {
			System.out.println("lll-->" + p);
		}

		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "visible", "image" });
		JSONArray linkListJsonArray = JSONArray.fromObject(linkList, config);
		JSONObject linkJsonObject = new JSONObject();
		linkJsonObject.put("linkTotal", linkService.selectTotalCount(null));
		linkJsonObject.put("linkList", linkListJsonArray);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(linkJsonObject.toString());
	}

	/**
	 * 查找
	 * @throws IOException
	 */
	public void search() throws IOException {
		try {
			start = parseIndex(start, limit);
			Map<String, Object> where = new HashMap<String, Object>();
			where.put(" entity.visible = ", new Boolean(getVisible()));

			System.out.println("url-->" + url);
			System.out.println("fromDate-->" + getFromDate());
			System.out.println("toDate-->" + getToDate());

			if (!"".equals(url.trim())) {
				where.put(" entity.url like ", url);
			}
			if (!"".equals(getFromDate().trim())) {
				if ("".equals(getToDate().trim())) {
					where.put(" entity.createDate between ", getFromDate()
							+ " 00:00:00' and '"
							+ getFormatDate(new Date(), YYYY_MM_DD_HH_MM_SS));
				} else {
					where.put(" entity.createDate between ", getFromDate()
							+ " 00:00:00' and '" + getToDate() + " 23:59:59");
				}
			}

			setLinkList(linkService.list(Link.class, getStart(), getLimit(),
					where, new Object[] { " entity.id desc " }));

			JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
			config.setExcludes(new String[] { "visible", "image" });
			JSONArray linkListJsonArray = JSONArray.fromObject(linkList, config);
			JSONObject linkJsonObject = new JSONObject();
			linkJsonObject.put("linkTotal", linkService.selectTotalCount(null));
			linkJsonObject.put("linkList", linkListJsonArray);
			System.out.println("linkJsonObject-->" + linkJsonObject.toString());
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(linkJsonObject.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查出关联图片
	 * @throws IOException
	 */
	public void image() throws IOException {
		try {
			JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
			config.setExcludes(new String[] { "createDate", "id", "visible" });
			JSONArray imagesJsonArray = JSONArray.fromObject(imageService
					.loadByName(imageName));
			JSONObject imagesJsonObject = new JSONObject();
			imagesJsonObject.put("image", imagesJsonArray);
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(imagesJsonObject.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加载通过id
	 * @throws IOException
	 */
	public void load() throws IOException {
		Link p = linkService.load(Link.class, link.getId());
		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "visible", "image" });
		JSONObject linkJsonObject = JSONObject.fromObject(p, config);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(linkJsonObject.toString());
	}

	/**
	 * 更新
	 * @throws IOException
	 */
	public void update() throws IOException {
		if (link != null) {
			Image image = handleImageUpload(linkImage, linkImageFileName,
					"LinkImage", BUFFER_SIZE);
			if (image != null) {
				imageService.save(image);
				link.setImage(imageService.loadByName(image.getName()));
			} else {
				image = imageService.loadByName(imageName);
				link.setImage(image);
			}
			linkService.update(link);
			imageService.delete(imageService.loadByName(imageName));
			initService.minLinks(session);
			result = "{'success':'true'}";
		} else {
			result = "{'success':'false'}";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(result);
	}

	/**
	 * 删除
	 * @throws IOException
	 */
	public void delete() throws IOException {
		try {
			if ("delete".equals(getMode())) {
				linkService.delete(link);
				imageService.delete(imageService.loadByName(imageName));
				initService.minLinks(session);
				result = "{'result':'delete'}";
			} else if ("update".equals(getMode())) {
				linkService.update(Link.class, new Object[] { link.getId() },
						false);
				initService.minLinks(session);
				result = "{'result':'update'}";
			} else {
				result = "{'result':'none'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 回收
	 * @throws IOException
	 */
	public void recover() throws IOException {
		try {
			if (link != null) {
				linkService.update(Link.class, new Object[] { link.getId() },
						true);
				initService.minLinks(session);
				result = "{'success':'true'}";
			} else {
				result = "{'success':'false'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Resource
	public void setLinkService(LinkService linkService) {
		this.linkService = linkService;
	}

	public LinkService getLinkService() {
		return linkService;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setLink(Link link) {
		this.link = link;
	}

	public Link getLink() {
		return link;
	}

	public void setLinkImage(File linkImage) {
		this.linkImage = linkImage;
	}

	public File getLinkImage() {
		return linkImage;
	}

	public void setLinkImageFileName(String linkImageFileName) {
		this.linkImageFileName = linkImageFileName;
	}

	public String getLinkImageFileName() {
		return linkImageFileName;
	}

	public void setLinkImageContentType(String linkImageContentType) {
		this.linkImageContentType = linkImageContentType;
	}

	public String getLinkImageContentType() {
		return linkImageContentType;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getStart() {
		return start;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getLimit() {
		return limit;
	}

	public void setVisible(String visible) {
		this.visible = visible;
	}

	public String getVisible() {
		return visible;
	}

	public void setLinkList(List<Link> linkList) {
		this.linkList = linkList;
	}

	public List<Link> getLinkList() {
		return linkList;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUrl() {
		return url;
	}

	public void setFromDate(String fromDate) {
		this.fromDate = fromDate;
	}

	public String getFromDate() {
		return fromDate;
	}

	public void setToDate(String toDate) {
		this.toDate = toDate;
	}

	public String getToDate() {
		return toDate;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getMode() {
		return mode;
	}

	@Resource
	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public ImageService getImageService() {
		return imageService;
	}

	public void setImageName(String imageName) {
		this.imageName = imageName;
	}

	public String getImageName() {
		return imageName;
	}

	@Resource
	public void setInitService(InitService initService) {
		this.initService = initService;
	}

	public InitService getInitService() {
		return initService;
	}

	@Override
	public void setSession(Map<String, Object> arg0) {
		this.session = arg0;
	}
}
